<?php
/*
 * @author eBIZ Team <dev@jungo.com.cn>
 * @copyright  Copyright (c) , ShenZhen JunGO Technology Co., Ltd. All rights reserved.
 * @license  Commercial authorization, unauthorized use and modification are prohibited
 * @url www.jungo.com.cn
 */

namespace ckeeper\http;



use ckeeper\utils\ManagerActionRecorder;
use Selibra\Di\Annotations\Autowired;
use Selibra\Di\Annotations\Component;
use Selibra\Di\DI;
use Selibra\Http\Annotations\Controller;
use Selibra\Http\Annotations\Route;
use Selibra\Model\EntityProxy;
use ckeeper\db\Transaction;
use ckeeper\entity\RoleEntity;
use ckeeper\services\RightsService;
use ckeeper\services\RoleService;

#[Controller("/system/role", Role::class)]
#[Component]
class Role extends http
{

    /**
     * @var RoleService
     */
    #[Autowired]
    protected RoleService $roleService;

    #[Route("/")]
    public function index()
    {
        $search = $this->getRequest()->getGet('search');
        $roleList = $this->roleService->searchRole($search);
        $roles = [];
        foreach ($roleList as $roleEntity) {
            $role = EntityProxy::entityConversionToArray($roleEntity);
            $role['status'] = $roleEntity->getStatus() === RoleService::STATUS_ENABLE;
            $role['create_time'] = date('Y-m-d H:i:s', $roleEntity->getCreateTime());
            $roles[] = $role;
        }
        return $this->success("获取成功", [
            'roles' => $roles
        ]);
    }


    /**
     * 添加角色
     * @return mixed
     */
    #[Route("/add", "POST")]
    public function add()
    {
        $name = $this->getRequest()->getPost('name');
        $description = $this->getRequest()->getPost('description');
        $status = $this->getRequest()->getPost('status') ? 1 : 0;
        if (empty($name)) {
            return $this->error("请输入角色名称",null,ERR_10005);
        }
        $roleEntity = new RoleEntity();
        $roleEntity->setName($name);
        // 状态
        $roleEntity->setStatus($status ? RoleService::STATUS_ENABLE : RoleService::STATUS_DISABLE);
        // 非必选，没有填的情况下传默认值就可以
        if (!empty($description)) {
            $roleEntity->setDescription($description);
        }
        // 保存
        Transaction::begin();
        try {
            $roleId = $this->roleService->addRole($roleEntity);
            if (empty($roleId)) {
                throw new \Exception("添加失败:" . $roleId);
            }

            // 记录操作日志
            ManagerActionRecorder::info(
                $this->manager->getUuid(),
                'roleAdd',
                '添加角色',
                $this->getRequest(),
                [
                    'id' => $roleId,
                ]
            );
            Transaction::commit();
        } catch (\Exception $exception) {
            Transaction::rollback();
            return $this->error('角色添加失败',null,ERR_10007);
        }
        return $this->success('角色{' . $roleEntity->getName() . '}添加成功');
    }


    /**
     * 修改状态
     * @return mixed
     */
    #[Route("/updateStatus", "POST")]
    public function updateStatus()
    {
        $id = $this->getRequest()->getPost('id');
        $value = $this->getRequest()->getPost('value');
        if (empty($id)) {
            return $this->error("参数缺失",null,ERR_10005);
        }
        $roleEntity = $this->roleService->getRoleById($id);
        if (empty($roleEntity)) {
            return $this->error("角色不存在",null,ERR_10008);
        }
        $value = !empty($value) ? RoleService::STATUS_ENABLE : RoleService::STATUS_DISABLE;
        // 修改的值的名称
        $keyDescription = '角色{' . $roleEntity->getName() . '}状态';
        Transaction::begin();
        try {
            $updateResult = $this->roleService->updateRoleData($id, 'status', $value);
            if (empty($updateResult)) {
                throw new \Exception($keyDescription . "修改失败:" . $updateResult);
            }

            // 记录操作日志
            ManagerActionRecorder::info(
                $this->manager->getUuid(),
                'roleUpdateStatus',
                $keyDescription . '修改为' . $value,
                $this->getRequest(),
                [
                    'id' => $id,
                    'key' => 'status',
                    'value' => $value
                ]
            );
            Transaction::commit();
        } catch (\Exception $exception) {
            Transaction::rollback();
            return $this->error($keyDescription . '修改失败',null,ERR_10007);
        }
        return $this->success($keyDescription . '修改成功');
    }


    /**
     * 修改角色信息
     * @return mixed
     */
    #[Route("/updateData", "POST")]
    public function updateData()
    {
        $id = $this->getRequest()->getPost('id');
        $name = $this->getRequest()->getPost('name');
        $description = $this->getRequest()->getPost('description');

        if (empty($id) || empty($name)) {
            return $this->error("参数缺失",null,ERR_10005);
        }
        $roleEntity = $this->roleService->getRoleById($id);
        if (empty($roleEntity)) {
            return $this->error("角色不存在",null,ERR_10008);
        }
        // 修改值
        $roleEntity->setName($name)
            ->setDescription(!empty($description) ? $description : ':null');

        // 修改的值的名称
        Transaction::begin();
        try {
            $updateResult = $this->roleService->updateRole($roleEntity);
            if (empty($updateResult)) {
                throw new \Exception("修改失败:" . $updateResult);
            }

            // 记录操作日志
            ManagerActionRecorder::info(
                $this->manager->getUuid(),
                'roleUpdate',
                '角色{' . $roleEntity->getName() . '}信息修改',
                $this->getRequest(),
                EntityProxy::entityConversionToArray($roleEntity)
            );
            Transaction::commit();
        } catch (\Exception $exception) {
            Transaction::rollback();
            return $this->error('角色{' . $roleEntity->getName() . '}修改失败：' . $exception->getMessage(),null,ERR_10007);
        }
        return $this->success('角色{' . $roleEntity->getName() . '}信息修改成功');
    }


    /**
     * 删除角色
     * @return mixed
     */
    #[Route("/delete", "DELETE")]
    public function delete()
    {
        $id = $this->getRequest()->getDelete('id');
        if (empty($id)) {
            return $this->error("参数缺失",null,ERR_10005);
        } elseif ($id == 1) {
            return $this->error("不允许删除超级管理员",null,ERR_10009);
        }
        $ids = explode(',', $id);
        if (count($ids) > 1) {
            $roleEntity = new RoleEntity();
            $roleEntity->setName('多选');
        } else {
            $roleEntity = $this->roleService->getRoleById($id);
        }
        Transaction::begin();
        try {
            $updateResult = $this->roleService->deleteRoleByIds($ids);
            if (empty($updateResult)) {
                throw new \Exception("删除失败:" . $updateResult);
            }

            // 记录操作日志
            ManagerActionRecorder::info(
                $this->manager->getUuid(),
                'roleDelete',
                '角色{' . $roleEntity->getName() . '}删除',
                $this->getRequest(),
                [
                    'id' => $id
                ]
            );
            Transaction::commit();
        } catch (\Exception $exception) {
            Transaction::rollback();
            return $this->error('角色{' . $roleEntity->getName() . '}删除失败：' . $exception->getMessage());
        }
        return $this->success('角色{' . $roleEntity->getName() . '}删除成功');
    }


    /**
     * 获取角色权限
     * @return mixed
     */
    #[Route("/rights", "GET")]
    public function rights()
    {
        $role = $this->getRequest()->getGet('role');
        $roleEntity = $this->roleService->getRoleById($role);
        if (empty($roleEntity)) {
            return $this->error("角色不存在，请检查",null,ERR_10008);
        }

        /** @var RightsService $rightsService */
        $rightsService = DI::getObjectContext(RightsService::class);
        $rightsList = [];
        $moduleRights = $rightsService->getRightsByPid(0);
        $mergeCells = [];
        $row = 0;
        foreach ($moduleRights as $rights) {
            $childModuleRights = $rightsService->getRightsByPid($rights->getId());
            $mergeCells[] = [
                'row' => $row,
                'col' => 0,
                'rowspan' => count($childModuleRights),
                'colspan' => 1
            ];
            $row += count($childModuleRights);
            foreach ($childModuleRights as $childRights) {
                $nowRights = EntityProxy::entityConversionToArray($childRights);
                // 获取功能权限
                $functionRights = $rightsService->getRightsByPid($childRights->getId());
                $nowRights['parentRights'] = $rights;
                $functionRightsArray = [];
                foreach ($functionRights as $functionRightsItem) {
                    $functionRightsItemArray = EntityProxy::entityConversionToArray($functionRightsItem);
                    $functionRightsItemArray['parentRights'] = $nowRights['key'];
                    $functionRightsArray[] = $functionRightsItemArray;
                }
                $nowRights['functionRights'] = $functionRightsArray;
                $rightsList[] = $nowRights;
            }
        }
        return $this->success('获取成功', [
            'moduleRights' => $moduleRights,
            'rightsList' => $rightsList,
            'mergeCells' => $mergeCells,
            'rights' => explode(',', $roleEntity->getRights())
        ]);
    }


    /**
     * 修改角色权限
     * @return mixed
     */
    #[Route("/rightsUpdate", "POST")]
    public function rightsUpdate()
    {
        $role = $this->getRequest()->getPost('role');
        $rights = $this->getRequest()->getPost('rights');
        if (empty($role)) {
            return $this->error("参数缺失",null,ERR_10005);
        }
        $roleEntity = $this->roleService->getRoleById($role);
        if (empty($roleEntity)) {
            return $this->error("角色不存在，请检查",null,ERR_10008);
        }
        $roleEntity->setRights(!empty($rights) ? $rights : ':null');
        // 修改
        Transaction::begin();
        try {
            $updateResult = $this->roleService->updateRole($roleEntity);
            if (empty($updateResult)) {
                throw new \Exception("修改失败:" . $updateResult);
            }

            // 记录操作日志
            ManagerActionRecorder::info(
                $this->manager->getUuid(),
                'roleRightsUpdate',
                '角色{' . $roleEntity->getName() . '}修改权限',
                $this->getRequest(),
                EntityProxy::entityConversionToArray($roleEntity)
            );
            Transaction::commit();
        } catch (\Exception $exception) {
            Transaction::rollback();
            return $this->error('角色{' . $roleEntity->getName() . '}修改失败：' . $exception->getMessage(),null,10007);
        }
        return $this->success('角色{' . $roleEntity->getName() . '} 权限修改成功');
    }

}
